
import { _decorator, Component, Node, Button } from 'cc';
import { EventMgr } from './EventMgr';
/**UI脚本的父节点 */
export class UICtrl extends Component {

    protected view: any = {}; // 路径--->节点; this.view["路径"] --->获得节点;
    private messageArray:any[]=[];

    private loadAllNodeInView(root: any, path: string) {
        for(let i = 0; i < root.children.length; i ++) {
            this.view[path + root.children[i].name] = root.children[i];
            this.loadAllNodeInView(root.children[i], path + root.children[i].name + "/");
        }
    }

    onLoad(): void {
        // 遍历它下面所有子节点，然后将所有的节点路径---》节点对象生成到view表里面;
        this.loadAllNodeInView(this.node, "");
    }

    //消息机制
    public AddMessage(eventName: string){
        this.messageArray.push({eventName:eventName});
        EventMgr.Instance.AddEventListener(eventName, this, this.recvMsg);
    }
    /**
     * 发送消息
     * @param cmd 
     * @param data 
     */
    public send(cmd:string,data:any){
        EventMgr.Instance.Emit(cmd,data);
    }

    public recvMsg(cmd:string , data:any){
        
    }
    /**
     * 获取节点或者节点上的组件
     * @param path 路径
     * @param ctrl 组件类型
     * @returns 
     */
    public getChildOrComponent(path:string,ctrl:any=null){
        let childNode:any = this.node.getChildByPath(path);
        if(ctrl!=null){
            let component=childNode.getComponent(ctrl);
            if(component !=null){
                return component;
            }else{
                console.error(path+"上不存在相关组件");
                return null;
            }
        }
        return childNode;
    }

    onDestroy(): void {
        for (let i = 0; i < this.messageArray.length; i++) {
            const element = this.messageArray[i];
            EventMgr.Instance.RemoveListenner(element.eventName,this,this.recvMsg);
        }
        this.messageArray = null;
    }

    // 按钮事件
    public AddButtonListener(viewName: string, caller: any, func: any) {
        var view_node = this.view[viewName];
        
        if (!view_node) {
            return;
        }
        
        var button = view_node.getComponent(Button);
        if (!button) {
            return;
        }

        view_node.on("click", func, caller);
    }

    // 其他UI事件, ....
}


